<template>
  <div class="van-infinitescroll" @scroll="scrollEvent">
    <slot></slot>
  </div>
</template>

<script lang='ts'>
import { defineComponent } from "vue";
export interface InfiniteScrollProps {
  /** 是否可以无限加载 */
  loadable: boolean;
  /** 距离顶部多少像素的时候触发加载 */
  distance?: number;
  /** 滚动加载事件 */
  infiniteEvent?: () => void;
}
export default defineComponent({
  /** 无限滚动 */
  name: "InfiniteScroll",
  props: {
    loadable: {
      default: false,
      type: Boolean,
      required: true,
    },
    distance: {
      default: 10,
      type: Number,
    },
    infiniteEvent: {
      type: Function,
      default: () => new Function(),
    },
  },
  setup(props: InfiniteScrollProps | any) {
    const scrollEvent = (e: any) => {
      const { scrollTop, scrollHeight, clientHeight } =
        e.target as HTMLDivElement;
      if (
        scrollTop + clientHeight >= scrollHeight - (props.distance || 10) &&
        props.loadable
      ) {
        props?.infiniteEvent?.();
      }
    };
    return {
      scrollEvent,
    };
  },
});
</script>

<style lang='scss' scoped>
.van-infinitescroll {
  width: 100%;
  height: 100%;
  overflow-x: hidden;
  overflow-y: auto;
}
</style>